package com.example.login;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.example.model.api.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class OAuthTokenService {
    @Autowired
    private Environment environment;

    public Result<Map<String, Object>> getAccessToken(String clientId, String clientSecret, String username, String password) {
        HashMap<String, Object> objectHashMap = new HashMap<>();
        objectHashMap.put("grant_type", AuthorizationGrantType.PASSWORD.getValue());
        objectHashMap.put("username", username);
        objectHashMap.put("password", password);
        objectHashMap.put("scope", "message.read");
        String body = HttpRequest.post(environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri") + "/oauth2/token")
                .basicAuth(clientId, clientSecret)
                .form(objectHashMap)
                .execute().body();

        Result<Map<String, Object>> ok = new Result<Map<String, Object>>().ok(JSONUtil.toBean(body, Map.class));
        return ok;
    }
}